<template>
  <div class="order-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNumber" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="景区名称">
          <el-input v-model="searchForm.scenicName" placeholder="请输入景区名称" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.state" placeholder="请选择状态" clearable>
            <el-option label="待支付" :value="0" />
            <el-option label="待使用" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已取消" :value="3" />
            <el-option label="已退款" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <el-table :data="orderList" border style="width: 100%">
      <el-table-column prop="orderNumber" label="订单号" width="180" />
      <el-table-column prop="scenicName" label="景区名称" width="150" />
      <el-table-column prop="ticketCount" label="门票数量" width="100" />
      <el-table-column prop="totalAmount" label="订单金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="state" label="订单状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.state)">
            {{ getStatusText(scope.row.state) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button 
            size="small" 
            type="primary" 
            @click="handleDetail(scope.row)"
            >查看详情</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleCancel(scope.row)"
            v-if="scope.row.state == 0"
            >取消订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { orderAPI } from '@/utils/api'

// 搜索表单
const searchForm = reactive({
  orderNumber: '', // 订单号
  scenicName: '', // 景区名称
  state: null // 状态，使用null而不是空字符串
})

// 订单列表数据
const orderList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知时间';
  
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) return dateTimeStr; // 如果日期无效，返回原字符串
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (err) {
    console.error('日期格式化错误:', err);
    return dateTimeStr; // 出错时返回原字符串
  }
};

// 获取订单列表
const getOrderList = () => {
  console.log('获取订单列表，参数:', {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    ...searchForm
  });
  console.log('搜索表单状态类型:', typeof searchForm.state, searchForm.state);
  
  // 如果有搜索条件则调用搜索接口，否则调用列表接口
  const hasSearchParams = searchForm.orderNumber || searchForm.scenicName || searchForm.state !== null;
  
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value
  };
  
  // 添加搜索条件
  if (searchForm.orderNumber) params.orderNumber = searchForm.orderNumber;
  if (searchForm.scenicName) params.scenicName = searchForm.scenicName;
  if (searchForm.state !== null) params.state = searchForm.state;
  
  const apiMethod = hasSearchParams ? orderAPI.search : orderAPI.getList;
  
  apiMethod(params).then(res => {
    console.log('订单列表响应:', res);
    if (res.data.code === 200) {
      // 处理API返回的数据
      const responseData = res.data.data;
      
      if (responseData.records) {
        // MyBatis Plus分页格式
        orderList.value = responseData.records;
        total.value = responseData.total;
      } else if (Array.isArray(responseData)) {
        // 数组格式
        orderList.value = responseData;
        total.value = responseData.length;
      } else {
        // 其他情况
        orderList.value = [];
        total.value = 0;
        console.error('无法识别返回的数据格式:', responseData);
      }
    } else {
      ElMessage.error(res.data.message || '获取订单列表失败');
      orderList.value = [];
      total.value = 0;
    }
  }).catch(err => {
    console.error('获取订单列表失败:', err);
    ElMessage.error('获取订单列表失败');
    orderList.value = [];
    total.value = 0;
  });
}

// 获取订单状态样式
const getStatusType = (state) => {
  console.log('状态类型检查:', typeof state, state);
  const map = {
    0: 'danger',   // 待支付
    1: 'warning',  // 待使用
    2: 'success',  // 已完成
    3: 'info',     // 已取消
    4: 'primary'   // 已退款
  };
  return map[state] || 'info';
}

// 获取订单状态文本
const getStatusText = (state) => {
  const map = {
    0: '待支付',
    1: '待使用',
    2: '已完成',
    3: '已取消',
    4: '已退款'
  };
  return map[state] || '未知状态';
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getOrderList();
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderNumber = '';
  searchForm.scenicName = '';
  searchForm.state = null;
  currentPage.value = 1;
  getOrderList();
}

// 查看详情
const handleDetail = (row) => {
  // 根据订单号获取详情
  orderAPI.getDetail(row.orderNumber).then(res => {
    if (res.data.code === 200) {
      const detail = res.data.data;
      
      // 显示详情对话框
      ElMessageBox.alert(
        `<div class="order-detail">
          <p><strong>订单号:</strong> ${detail.orderNumber}</p>
          <p><strong>景区名称:</strong> ${detail.scenicName || '未知景区'}</p>
          <p><strong>门票数量:</strong> ${detail.ticketCount || 1}</p>
          <p><strong>订单金额:</strong> ¥${detail.totalAmount}</p>
          <p><strong>用户ID:</strong> ${detail.userId}</p>
          <p><strong>下单时间:</strong> ${formatDateTime(detail.createTime)}</p>
          <p><strong>游玩日期:</strong> ${detail.playDate ? formatDateTime(detail.playDate).split(' ')[0] : '未设置'}</p>
          <p><strong>订单状态:</strong> ${getStatusText(detail.state)}</p>
        </div>`,
        '订单详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          callback: (action) => {
            // 不需要特别处理，只是为了防止点击取消时报错
            console.log('详情对话框操作:', action);
          }
        }
      );
    } else {
      ElMessage.error(res.data.message || '获取订单详情失败');
    }
  }).catch(err => {
    console.error('获取订单详情失败:', err);
    ElMessage.error('获取订单详情失败');
  });
}

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm(
    '确认取消该订单吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    console.log('准备取消订单:', row.orderNumber);
    
    orderAPI.cancel(row.orderNumber).then(res => {
      console.log('取消订单响应:', res);
      if (res.data.code === 200) {
        ElMessage.success('订单已取消');
        getOrderList();
      } else {
        ElMessage.error(res.data.message || '取消订单失败');
      }
    }).catch(err => {
      console.error('取消订单失败:', err);
      ElMessage.error('取消订单失败');
    });
  }).catch(() => {
    // 用户点击了取消按钮，不做任何处理
    console.log('用户取消了操作');
  });
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  getOrderList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getOrderList()
}

onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-detail p {
  margin: 8px 0;
}
</style>